<template>
  <div class="meterage-manage-detail">
    <el-dialog width="70%" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag class="image-progress-detail" :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <span slot="title">
        <i class="iconfont icon-zhiliangguanli1"></i>
        <span>{{title}}</span>
      </span>
      <el-tabs v-model="activeName" v-show="detailType!=='build'&&detailType!=='edit'">
        <el-tab-pane label="基本信息" name="first"></el-tab-pane>
        <el-tab-pane label="审批记录" name="second" v-if="detailType!=='build'&&formBaseData.needRectification=='1'"></el-tab-pane>
      </el-tabs>
      <div class="WholeScroll" style="max-height: 650px; overflow: auto;padding: 0 15px;">
        <cmsDetailRowFile v-show="activeName == 'first'&&detailType!='build'" :tableFileList="formBaseData.fileList" :showTable="showRowTable"></cmsDetailRowFile>
        <el-form :model="formBaseData" ref="formBaseData" v-show="activeName == 'first'" :rules="formBaseRules" v-loading="isLoading">
          <el-row>
            <el-col :span="12">
              <el-form-item label="标段" prop="sectionId" :label-width="formlabelWidth">
                <el-input disabled size="small" v-model="formBaseData.sectionName" placeholder="请输入检查人员"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="检查日期" prop="inspectionTime" :label-width="formlabelWidth">
                <el-date-picker :disabled="detailType === 'check' || detailType === 'approve'" style="width: 100%;" v-model="formBaseData.inspectionTime" type="date" :picker-options="pickerOptions0" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检查人员" prop="inspector" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.inspector" placeholder="请输入检查人员" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :span="24">
            <!-- <el-col :span="12">
              <el-form-item label="巡查级别" prop="inspectionLevel" :label-width="formlabelWidth">
                <el-select style="width: 100%;" v-model="formBaseData.inspectionLevel"
                           placeholder="请选择巡查级别"
                           :disabled="detailType === 'check'||detailType==='approve'">
                  <el-option
                    v-for="(item, i) in inspectionLevelList"
                    :key="i"
                    :label="item.name"
                    :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>-->

            <el-col :span="12">
              <el-form-item label="检查单位" prop="constructionTeam" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.constructionTeam" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检查依据" prop="checkBasis" :label-width="formlabelWidth">
                <el-input size="small" v-model="formBaseData.checkBasis" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="位置" prop="location" :label-width="formlabelWidth">
                <div class="flex-row-center">
                  <el-input style="flex:1 1 0%;" size="small" v-model="formBaseData.location" placeholder="请输入位置信息" :disabled="detailType === 'check'||detailType==='approve'">
                  </el-input>
                  <!-- <el-input style="width: 27%;" size="small" v-model="formBaseData.longitude" placeholder="请输入经度信息" :disabled="detailType === 'check'||detailType==='approve'">
                    <template slot="prepend">经度</template>
                  </el-input> -->
                  <!-- <el-input style="width: 27%;" size="small" v-model="formBaseData.latitude" placeholder="请输入纬度信息" :disabled="detailType === 'check'||detailType==='approve'">
                    <template slot="prepend">纬度</template>
                  </el-input> -->
                  <el-button style="margin-left: 10px;" v-if="detailType=='build'|| detailType == 'edit'" class="dialog-normal-button" @click="showPicker()">获取位置
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item prop="note" label="检查说明" :label-width="formlabelWidth">
                <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" placeholder="" v-model="formBaseData.note" :disabled="detailType != 'build' && detailType != 'edit'">
                </el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <div class="content-box">
              <div class="left-box WholeScroll">
                <p :class="{ active: activeIndex == index }" @click="changeTab(index)" v-for="(item, index) in tabs" :key="index">{{ item }}</p>
              </div>
              <div class="right-box WholeScroll">
                <!-- 督办内容 -->
                <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules">
                  <div v-show="activeIndex == 0">
                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="检查结果" prop="isRectification" :label-width="formlabelWidth">
                          <el-radio-group style="margin-top: 5px" v-model="formBaseData.needRectification" :disabled="detailType === 'check'||detailType==='approve'" @change="needRectificationChange">
                            <el-radio label="1">需要整改</el-radio>
                            <el-radio label="2">无需整改</el-radio>
                          </el-radio-group>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item :prop="formBaseData.needRectification== '1'?'hiddenPartsAndDescribe':''" label="隐患部位及描述" :label-width="formlabelWidth">
                          <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="" v-model="formBaseData.hiddenPartsAndDescribe" :disabled="detailType === 'check'|| detailType === 'approve' ">
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-collapse v-model="activeCollapse" @change="handleChange">
                          <el-collapse-item name="1">
                            <template slot="title">
                              <div class="flex-align-center" style="width: 95%;">
                                <div>检查清单（<span style="color: #CB1221;">发现隐患数：{{formBaseData.hiddenDangersNumber}}</span>）
                                </div>
                                <div v-show="detailType != 'check'&&detailType !='approve'" class="hover-underline-changeBlue" @click.stop="selectworklist()">新增排查内容
                                </div>
                              </div>
                            </template>
                            <vxe-table ref="vxeCheckTable" empty-text='暂无数据' class="vxe-table-tree WholeScroll" border max-height="600" row-id="id" :data="formBaseData.items" :tree-config="{children: 'childList',indent: 30,transform: true,parentField: 'parentCode',rowField: 'code',expandAll: true  }" :checkbox-config="{ labelField: 'name' }" @checkbox-change="selectChangeEvent">
                              <vxe-column title="隐患类别/排查内容" tree-node>
                                <template #default="{ row }">
                                  <div v-if="row.hasOwnProperty('checkContent')">
                                    {{row.checkContent}}
                                  </div>
                                  <div v-else>
                                    {{row.name}}
                                  </div>
                                </template>
                              </vxe-column>
                              <vxe-column field="hiddenDangerLevel" title="隐患级别" width="10%"></vxe-column>
                              <vxe-column field="passStatus" title="通过状态" width="20%">
                                <template #default="{ row }">
                                  <div v-if="row.hasOwnProperty('checkContent')">
                                    <el-select style="width: 100%;" v-model="row.passStatus" @change="val=>updateData(val,row)" placeholder="" :disabled="detailType != 'build'&&detailType != 'edit'">
                                      <el-option v-for="(item, i) in passArr" :key="i" :label="item.name" :value="item.id">
                                      </el-option>
                                    </el-select>
                                  </div>
                                </template>
                              </vxe-column>
                              <!-- <vxe-column field="dutyArea" title="责任区域" width="15%">
                                <template #default="{ row }">
                                  <div v-if="detailType == 'build'|| detailType == 'edit'" @click="pOpen(row)">
                                    <el-input v-if="row.passStatus == '2'" v-model="row.dutyArea" class="tree-input"></el-input>
                                  </div>
                                  <div v-else>
                                    {{row.dutyArea}}
                                  </div>
                                </template>
                              </vxe-column> -->
                              <vxe-column title="操作" width="15%" v-if="detailType === 'build' || detailType === 'edit'">
                                <template #default="scope">
                                  <div class="btnGroup">
                                    <el-button type="danger" size="small" v-if="detailType !== 'check'" @click="removeRow(scope) ">删除
                                    </el-button>
                                  </div>
                                </template>
                              </vxe-column>
                            </vxe-table>
                          </el-collapse-item>
                          <el-collapse-item name="2">
                            <template slot="title">
                              <div class="flex-align-center" style="width: 95%;">
                                <div>检查附件</div>
                                <div v-show="detailType != 'check'&&detailType !='approve'" class="hover-underline-changeBlue" @click.stop="addNewFile(1)">新增附件
                                </div>
                              </div>
                            </template>
                            <cmsFileTableCanReName v-show="activeIndex == 0" ref="cmsFileTable_one" :buildUnitTable="buildUnitTable" :fileSystem="fileSystem" :detailId="detailId" :detailType="detailType" :buttonDelShow="buttonDelShow" :cantRename="cantRename()" :showNone="showNone" :buttonCheckShow="buttonCheckShow" :buttonUploadShow="buttonUploadShow" @change="val=>tableChange(val,'cmsFileTable_one')" limitType="jpg">
                            </cmsFileTableCanReName>

                          </el-collapse-item>
                        </el-collapse>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-show="activeIndex == 1">

                    <!--        <el-row>
                      <el-col :span="24">
                        <el-form-item label="是否下发整改通知单" prop="isNotice" :label-width="formlabelWidth">
                          <el-radio-group style="margin-top: 5px" v-model="formBaseData.isNotice"
                                          :disabled="detailType === 'check'||detailType==='approve'"
                          >
                            <el-radio label="1">发整改通知单</el-radio>
                            <el-radio label="2">不发</el-radio>
                          </el-radio-group>
                        </el-form-item>
                      </el-col>
                    </el-row>-->
                    <el-row>

                      <!-- 2023年12月7日，去掉 -->
                      <!-- <el-col :span="12">
                        <el-form-item prop="noticeNum" label="通知单编号" :label-width="formlabelWidth">
                          <el-input size="small" v-model="formBaseData.noticeNum" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                        </el-form-item>
                      </el-col> -->

                      <el-col :span="12">
                        <el-form-item label="签发日期" prop="dateIssue" :label-width="formlabelWidth">
                          <el-date-picker :disabled="detailType === 'check' || detailType === 'approve'" style="width: 100%;" v-model="formBaseData.dateIssue" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择日期时间">
                          </el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <!-- 2023年12月7日，去掉 -->
                    <!-- <el-row>
                       <el-col :span="12">
                        <el-form-item label="问题类型" prop="checkQuestionType" :label-width="formlabelWidth">
                          <el-select class="form-input" :disabled="detailType == 'check' || detailType === 'approve'" v-model="formBaseData.checkQuestionType" placeholder="选择问题类型" multiple filterable>
                            <el-option v-for="item in checkQuestionTypeArr" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col> 
                      <el-col :span="12">
                        <el-form-item label="工程类别" prop="worksCategory" :label-width="formlabelWidth">
                          <el-select class="form-input" :disabled="detailType == 'check' || detailType === 'approve'" v-model="formBaseData.worksCategory" placeholder="选择工程类别" multiple filterable>
                            <el-option v-for="item in worksCategoryArr" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col> 
                    </el-row>-->
                    <!-- 2023年12月7日，去掉 -->
                    <!-- <el-row>
                      <el-col :span="12">
                        <el-form-item prop="categoryName" label="工程名称" :label-width="formlabelWidth">
                          <el-input size="small" v-model="formBaseData.categoryName" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item prop="parts" label="整改部位" :label-width="formlabelWidth">
                          <el-input size="small" v-model="formBaseData.parts" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row> -->

                    <el-row>
                      <el-col :span="24">
                        <el-form-item prop="existingProblems" label="存在问题" :label-width="formlabelWidth">
                          <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="" v-model="formBaseData.existingProblems" :disabled="detailType === 'check'|| detailType === 'approve' ">
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <el-form-item prop="suggestedRectificationMeasures" label="整改要求" :label-width="formlabelWidth">
                          <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="" v-model="formBaseData.suggestedRectificationMeasures" :disabled="detailType === 'check'|| detailType === 'approve' ">
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="整改截止日期" prop="rectificationDeadline" :label-width="formlabelWidth">
                          <el-date-picker style="width:100%;" v-model="formBaseData.rectificationDeadline" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" :disabled="detailType === 'check'||detailType === 'approve'"></el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-show="activeIndex == 2">
                    <!-- <el-row>
              <el-col :span="24">
                   <el-form-item  label="隐患基本情况" required :label-width="formlabelWidth">
                     <el-input
                       class="fill"
                       type="textarea"
                       :autosize="{ minRows: 4, maxRows: 6}"
                       placeholder=""
                       v-model="formBaseData.hiddenInformation"
                       :disabled="detailType === 'check'|| (formBaseData.taskKey!='UserTask_1sci9cl'&&detailType != 'approve')
                       || (formBaseData.taskKey!='UserTask_1sci9cl'&&detailType == 'approve')"
                     >
                     </el-input>
                   </el-form-item>
                 </el-col>
                 </el-row>-->

                    <el-row>
                      <!--      <el-col :span="12">
                        <el-form-item label="整改开始日期"  :label-width="formlabelWidth">
                          <el-date-picker
                            style="width:100%;"
                            v-model="formBaseData.rectificationStartDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期"
                            :disabled="detailType === 'check'|| (formBaseData.taskKey!='UserTask_1sci9cl'&&detailType != 'approve')
                            || (formBaseData.taskKey!='UserTask_1sci9cl'&&detailType == 'approve')"
                          ></el-date-picker>
                        </el-form-item>
                      </el-col>-->
                      <el-col :span="12">
                        <el-form-item label="整改完成日期" required :label-width="formlabelWidth">
                          <el-date-picker style="width:100%;" v-model="formBaseData.rectificationCompletionDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" :disabled="detailType === 'check'|| this.formBaseData.zghf ">
                            ></el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="整改负责人" required :label-width="formlabelWidth">
                          <el-input size="small" v-model="formBaseData.headRectification" :disabled="detailType === 'check'|| this.formBaseData.zghf"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="回复单编号" required :label-width="formlabelWidth">
                          <el-input size="small" v-model="formBaseData.replyCode" :disabled="detailType === 'check'|| this.formBaseData.zghf "></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="整改结果" required :label-width="formlabelWidth">
                          <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="" v-model="formBaseData.rectificationMeasures" :disabled="detailType === 'check' || this.formBaseData.zghf"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-collapse v-model="activeCollapseTwo">
                          <el-collapse-item name="3">
                            <template slot="title">
                              <div class="flex-align-center" style="width: 95%;">
                                <div>整改后附件</div>
                                <div v-if=" !this.formBaseData.zghf&&detailType!=='check'" class="hover-underline-changeBlue" @click.stop="addNewFile(2)">新增附件
                                </div>
                              </div>
                            </template>
                            <cmsFileTableCanReName v-show="activeIndex == 2" ref="cmsFileTable_Two" :buildUnitTable="buildUnitTableTwo" :fileSystem="fileSystem" :detailId="detailId" :cantRename="cantRename2()" :detailType="detailType" :buttonDelShow="buttonDelShow" :showNone="showNone2" :isNeedInit="isNeedInit" :buttonCheckShow="buttonCheckShow" :buttonUploadShow="buttonUploadShow2" @change="val=>tableChange(val,'cmsFileTable_Two')">
                            </cmsFileTableCanReName>

                          </el-collapse-item>
                        </el-collapse>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-show="activeIndex == 3">
                    <el-row>
                      <el-col :span="24">
                        <el-form-item prop="acceptanceCondition" label="验收结果" :label-width="formlabelWidth">
                          <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="请输入验收结果" v-model="formBaseData.acceptanceCondition" :disabled="detailType === 'check' || this.formBaseData.zgys">
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-collapse v-model="activeCollapseThree">
                          <el-collapse-item name="4">
                            <template slot="title">
                              <div class="flex-align-center" style="width: 95%;">
                                <div>验收附件</div>
                                <div v-if="!this.formBaseData.zgys&&detailType!=='check'" class="hover-underline-changeBlue" @click.stop="addNewFile(3)">新增附件
                                </div>
                              </div>
                            </template>
                            <cmsFileTableCanReName v-show="activeIndex == 3" ref="cmsFileTable_Three" :buildUnitTable="buildUnitTableThree" :fileSystem="fileSystem" :detailId="detailId" :detailType="detailType" :cantRename="cantRename3()" :buttonDelShow="buttonDelShow" :showNone="showNone3" :isNeedInit="isNeedInit" :buttonCheckShow="buttonCheckShow" :buttonUploadShow="buttonUploadShow3" @change="val=>tableChange(val,'cmsFileTable_Three')">
                            </cmsFileTableCanReName>

                          </el-collapse-item>
                        </el-collapse>
                      </el-col>
                    </el-row>
                  </div>
                </el-form>
              </div>
            </div>
          </el-row>

          <el-row style="margin-top: 15px">
            <el-col :span="24">
              <bpmn-form v-if="isShowBpmn" ref="bpmnForm" proc-def-key="safetyRectificationProcess" :business-id="formBaseData.id" :url="url" :entity="formBaseData" :formlabelWidth="formlabelWidth" @complete="onComplete" :needInit="false" :variables="variables"></bpmn-form>
            </el-col>
          </el-row>
        </el-form>
        <el-tab-pane label="审批记录" name="second" v-show="activeName == 'second'&&formBaseData.procInstId">
          <wf-process :inst-id="formBaseData.procInstId" :isShowLastTime="false" :url="urlProcess" />
        </el-tab-pane>
      </div>

      <positon-picker :postDetail="showPickerObj" :isShowJW="false" @setPosition="setPosition"></positon-picker>
      <div slot="footer" class="dialog-footer">
        <pop-btn v-if="isShowBpmn" ref="btn" :key="formShow" proc-def-key="safetyRectificationProcess" :business-id="formBaseData.id" :readonly="readonly" :task-id="formBaseData.taskId" @save="onSave" @approve="onApprove" @apply="onApply" @cancel="cancel" />

        <template v-if="!isShowBpmn">
          <el-button size="small" type="primary" @click="handleClickDeal('submit')">
            <i class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button v-if="!isShowBpmn" size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>

    <el-dialog width='40%' title='选择责任区域' :visible.sync='showAreaSelectDialog' :modal-append-to-body='true' :close-on-click-modal='false' v-dialog-drag append-to-body>
      <span slot='title'>
        <span>选择责任区域</span>
      </span>
      <div class="WholeScroll" style="min-height: 500px;overflow-y: auto">
        <el-tree :data="areaList" :props="defaultProps" :check-strictly="true" default-expand-all :expand-on-click-node="false" @node-click="handleTreeNodeClick">
        </el-tree>
      </div>
    </el-dialog>

    <el-dialog width="70%" title="新增检查内容" class="addProjectDialog" :visible.sync="showContractListDialog" :modal-append-to-body="false" :close-on-click-modal="false" @close="closeDialogReset" v-dialog-drag :append-to-body="true">
      <div class="changecost_contract_list">
        <div class="body WholeScroll">
          <vxe-table v-if="showContractListDialog" ref="vxe-dialog-table" class="vxe-table-tree WholeScroll" show-overflow="ellipsis" border height="600" row-id="id" :data="contractListTable" :tree-config="{children: 'childList',indent: 30,parentField: 'parentCode',rowField: 'code' }" :checkbox-config="{ labelField: 'name',checkMethod:disabledFun, checkRowKeys: checkRowKeys }" @checkbox-change="selectChangeEvent">
            <vxe-column title="隐患类别/检查内容" tree-node type="checkbox" width="35%">
              <template #default="{ row }">
                <div v-if="!row.hasOwnProperty('childList')">
                  {{row.checkContent}}
                </div>
                <div v-else>
                  {{row.name}}
                </div>
              </template>
            </vxe-column>
            <vxe-column field="hiddenDangerLevel" title="等级"></vxe-column>
            <vxe-column field="rectificationTimeLimit" title="整改时限(天)"></vxe-column>
            <vxe-column field="rectificationRequirements" title="整改要求" width="40%">
              <template #default="{ row }">
                <el-tooltip class="item" effect="dark" :content="row.rectificationRequirements" placement="left">
                  <div>{{row.rectificationRequirements}}</div>
                </el-tooltip>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <template v-if="detailType === 'build'||detailType === 'edit'">
          <el-button size="small" type="primary" @click="handleClickDeal('selected')">
            <i class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('selectedcancel')"><i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
//  复制粘贴改下面的名字
import projectSectionInfo from '@/api/buss/common'
import WfProcess from '@/components/WorkFlow/process/index'
import msgUtil from '@/utils/msgUtil'
import startMixin from '@/mixins/wfStartMixin'
import approveMixin from '@/mixins/wfApproveMixin'
import PopBtn from '@/components/ExtBpmn/Btn/index'
import BpmnForm from '@/components/ExtBpmn/ExtForm/bpmn-form'
import safetyRectification from '@/api/buss/safetyRectification'
import sectionInfo from '@/api/buss/sectionInfo'
import crudDict from '@/api/system/dict'
import cmsTableChoose from '@/components/cms/cmsTableChoose'
import dept from "@/api/system/dept";

export default {
  name: `safe-patrol-manage-detail`,
  components: {
    WfProcess,
    BpmnForm,
    PopBtn,
    cmsTableChoose
  },
  mixins: [startMixin, approveMixin],
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  watch: {
    'formBaseData.items': {
      immediate: false,
      handler(val) {
        if (val.length > 0) {
          this.calculateNumberAndText()
        }
      },
      deep: true
    },
    postDetail(value) {
      if (value.type != 'check') {
        this.user = this.$store.getters.user
      }
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      this.title = '安全整改'
      if (value.search) { this.search = value.search }
      this.formBaseData.sectionId = value.search && value.search.sectionId
      this.formBaseData.sectionName = value.search && value.search.sectionName
      this.formBaseData.projectId = value.search && value.search.projectId
      this.formBaseData.projectName = value.search && value.search.projectName
      // 详情id
      this.detailBaseId = value.detailId ? value.detailId : ''
      if (this.detailType === 'approve') {
        this.isShowBpmn = true
      } else {
        this.isShowBpmn = false
      }
      this.$nextTick(() => {
        if (this.detailType !== 'build') {
          // this.initData()
          // 获取详情请求
          this.getDict()
          this.getDetail()
          if (this.formBaseData.projectId) {
            this.getCheckList()//获取检查清单
          }
          // this.getAreaList()//责任区域
        } else {
          // this.initData()
          this.initBtn()
          this.getCheckList()
          this.initUserInfo()
          // this.getAreaList()//责任区域
        }
      })
    },
    'formBaseData.needRectification': {
      handler(val) {
        if (val == '2') {//无需整改
          let arr = [
            '检查内容'
          ]
          this.$set(this, 'tabs', arr)
          this.isShowBpmn = false
        }
        if (val == '1') {//需要整改
          let arr = [
            '检查内容',
            '整改要求',
          ]
          if (this.formBaseData.taskKey == 'UserTask_1sci9cl') {
            arr.push('整改回复')
          }
          if (this.formBaseData.taskKey == 'UserTask_0t9gy8c' || this.formBaseData.taskKey == 'UserTask_0bm9j9l' || this.formBaseData.taskKey == 'end') {
            arr.push('整改回复')
            arr.push('整改验收')
          }
          this.$set(this, 'tabs', arr)
          this.$set(this, 'tabs', arr)
          this.isShowBpmn = true
        }
      }
    }
  },
  data() {
    return {
      treeProps: { children: 'children' },
      activeCollapse: ['1', '2'],
      activeCollapseTwo: ['3'],
      activeCollapseThree: ['4'],
      contractListTable: [],
      checkRowKeys: [],
      showContractListDialog: false,
      showAreaSelectDialog: false,
      chooseRow: {},
      checkQuestionTypeArr: {},
      worksCategoryArr: {},
      passArr: [{
        name: '通过',
        id: '1'
      }, {
        name: '不通过',
        id: '2'
      }],
      areaList: [],
      pickerOptions0: {
        disabledDate: (time) => {
          if (time.getTime() > Date.now() - 8.64e6) {
            return true
          }
        }
      },
      selectedIds: [],
      activeIndex: 0,
      tabs: [
        '排查内容'
      ],
      isShowBpmn: false,
      detailBaseId: '',
      readonly: false,
      variables: { initiator: 1 },
      entity: {},
      fileList: [],
      checkInitShow: false,
      companyTree: [], // 公司下拉
      projectTree: [], // 项目下拉
      sectionTree: [], // 标段下拉
      wfNode: {},
      url: 'buss/safetyRectification/node/attribute',
      urlProcess: 'buss/safetyRectification/process',
      title: '',
      search: {},
      isLoading: false,
      vm: this,
      //dialog宽度
      dialogColumn: '2',
      //存放对应按钮数量的文件list
      fileListArray: [],
      fileListArray2: [],
      inspectionLevelList: [],
      urgencyList: [],
      secondTableData: [],
      formBaseData: {
        initiator: 1,
        needRectification: '2',
        hiddenPartsAndDescribe: '',
        hiddenDangersNumber: '0',
        projectName: '',
        sectionName: '',
        inspector: '',
        inspectionTime: '',
        inspectionLevel: '',
        longitude: '',
        latitude: '',
        suggestedRectificationMeasures: '',
        rectificationDeadline: '',
        hiddenInformation: '',
        projectId: '',
        sectionId: '',
        rectificationMeasures: '',
        rectificationStartDate: '',
        rectificationCompletionDate: '',
        headRectification: '',
        acceptanceCondition: '',
        //  标题
        title: '',
        rectificationDate: '',
        isAuditUpdate: 0,
        opinion: '',
        checkUser: '',
        checkDate: '',
        constructionTeam: '',
        checkBasis: '',
        isRectification: '2',
        problemType: '',
        urgency: '',
        lon: '',
        lat: '',
        location: '',
        locationAll: '',
        checkTime: '',
        items: [],
        fileStr: '',
        note: '',
        isNotice: '2',
        noticeNum: '',
        dateIssue: '',
        checkQuestionType: '',
        worksCategory: '',
        categoryName: '',
        parts: '',
        existingProblems: '',
        headPerson: '',
        replyCode: '',
        zghf: true,
        zgys: true
      },
      file1: [],
      file2: [],
      dict: { rectifications: [{ label: '限期整改', value: '1' }, { label: '否', value: '2' }] },
      //  被选中的用于新增的项目
      showSelectDialog: false,
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      isAudit: '',
      detailId: '', // 当前详情的id
      activeName: 'first', //
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      formlabelWidth: '165px', // 表单左侧标题宽度
      //  当前操作数据的所属合同号
      contractId: null,
      // 文件系统的参数
      fileSystem: {
        attachId: {
          partOne: ''
        },
        sys: 'buss',
        module: 'safetyCheckInspection',
        entityClass: 'safetyCheckInspection',
        viewByAnon: true,
        longLife: false,
        part: {
          partOne: 'partOne'
        }
      },
      treePopover: false,
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'areaName'
      },
      showPickerObj: {
        show: false
      },
      formBaseRules: {
        companyId: [
          { required: true, message: '请选择' + '公司', trigger: 'change' }
        ],
        projectId: [
          { required: true, message: '请选择' + '项目', trigger: 'change' }
        ],
        inspectionLevel: [
          { required: true, message: '请选择巡查级别', trigger: 'change' }
        ],
        sectionId: [
          { required: true, message: '请选择' + '标段', trigger: 'change' }
        ],
        hiddenPartsAndDescribe: [
          { required: true, message: '请输入' + '隐患部位及描述', trigger: 'blur' }
        ],
        constructionTeam: [{ required: true, message: '请填写检查单位', trigger: 'blur' }],
        inspectionTime: [{ required: true, message: '请填写检查日期', trigger: 'blur' }],
        inspector: [{ required: true, message: '请填写检查人员', trigger: 'blur' }],
        isRectification: [{ required: true, message: '请选择是否限期整改', trigger: 'blur' }],
        rectificationCompletionDate: [{ required: true, message: '整改完成日期', trigger: 'blur' }],
        rectificationDeadline: [{ required: true, message: '整改截止日期', trigger: 'blur' }],
        suggestedRectificationMeasures: [{ required: true, message: '整改要求', trigger: 'blur' }],
        /* categoryName: [{ required: true, message: '请填写工程名称', trigger: 'blur' }],
         parts: [{ required: true, message: '请填写整改部位', trigger: 'blur' }],*/
        replyCode: [{ required: true, message: '请填写回复单号', trigger: 'blur' }],
        checkQuestionType: [{ required: true, message: '请选择问题类型', trigger: 'blur' }],
        worksCategory: [{ required: true, message: '请选择工程类型', trigger: 'blur' }],

        rectificationDate: [
          { required: true, message: '请填写限期整改日期', trigger: 'blur' }
        ],
        isNotice: [{ required: true, message: '请选择是否下发通知单', trigger: 'blur' }],
        noticeNum: [{ required: true, message: '请填写通知单编号', trigger: 'blur' }],
        dateIssue: [{ required: true, message: '请选择签发日期', trigger: 'blur' }],
        existingProblems: [
          { required: true, message: '请填写存在问题', trigger: 'blur' },
        ],
      }, // 表单基本信息验证
      meterageManageDetail: '',
      /**
       * 审批配置数据
       * */
      auditConfigData: {
        //  实体基本数据
        baseData: {},
        //  基本请求地址
        urlBase: '',
        //  是否显示
        show: false,
        //  提交数据成功时候的回调函数
        submitCallBack: null,
        //  选择了动作时的回调函数
        selActionCallBack: null
      },
      //  显示审批提交按钮
      showAuditBtn: false,
      selectTreeChildren: [],
      taskDefKey: '',
      entityId: '',
      buildUnitTable: [],
      buildUnitTableTwo: [],
      buildUnitTableThree: [],
      tableLong: 0,
      isNeedInit: false,
      vxeTableCheckData: [],
      matherData: []
    }
  },

  created() {
    this.getDict()
    this.getInspectionLevel()
  },
  methods: {
    initUserInfo() {
      if (this.detailType == 'build') {
        var user = JSON.parse(localStorage.getItem('sysUser'))
        this.formBaseData.inspector = user.name
        this.formBaseData.constructionTeam = user.companyName
      }
    },
    //整改回复
    getZghf() {
      let sysUser = JSON.parse(localStorage.getItem('sysUser'))
      this.formBaseData.headRectification = sysUser.name
      if (this.formBaseData.taskKey) {
        if (this.formBaseData.taskKey == 'UserTask_1sci9cl' || this.formBaseData.taskKey == 'UserTask_1sci9cl') {
          this.formBaseData.zghf = false
        } else {
          this.formBaseData.zghf = true
        }
      } else {
        this.formBaseData.zghf = true
      }

    },
    //整改验收
    getZgys() {
      if (this.formBaseData.taskKey) {
        if (this.formBaseData.taskKey == 'UserTask_0t9gy8c' || this.formBaseData.taskKey == 'UserTask_0bm9j9l') {
          this.formBaseData.zgys = false
        } else {
          this.formBaseData.zgys = true
        }

      } else {
        this.formBaseData.zgys = true
      }
      console.log("this.formBaseData.zgys=", this.formBaseData.zgys)
    },
    cantRename() {
      //不可编辑的条件
      let flag = false
      if (this.detailType == 'check' || this.detailType == 'approve') {
        flag = true
      }
      if (this.detailType == 'check') {
        flag = true
      }
      return flag

    },
    cantRename2() {
      //不可编辑的条件
      //cantRename 为 true 为不可编辑
      let flag = false
      if (this.detailType == 'approve' && this.formBaseData.taskKey == 'UserTask_1sci9cl') {
        flag = false
      }
      if (this.formBaseData.taskKey != 'UserTask_1sci9cl') {
        flag = true
      }
      if (this.detailType == 'check') {
        flag = true
      }
      return flag

    },
    cantRename3() {
      //不可编辑的条件
      //cantRename 为 true 为不可编辑
      let flag = false
      if (this.detailType == 'approve' && this.formBaseData.taskKey == 'UserTask_0t9gy8c' ||
        this.detailType == 'approve' && this.formBaseData.taskKey == 'UserTask_0bm9j9l') {
        flag = false
      } else {
        flag = true
      }
      if (this.detailType == 'check') {
        flag = true
      }

      return flag

    },
    getDict() {
      this.checkQuestionTypeArr = []
      crudDict.getByCode('checkQuestionType').then(res => {
        if (res.code == 200) {
          this.checkQuestionTypeArr = res.data
        }
      })
      this.worksCategoryArr = {}
      crudDict.getByCode('worksCategory').then(res => {
        if (res.code == 200) {
          this.worksCategoryArr = res.data

        }


      })

    },
    checkoutArea() {
      let canApply = true
      this.formBaseData.items.forEach((item, index) => {
        if (item.hasOwnProperty('passStatus') && item.passStatus == '2' && item.hasOwnProperty('dutyArea') && item.dutyArea == '') {
          canApply = false
        }
        if (item.hasOwnProperty('passStatus') && item.passStatus == '2' && !item.hasOwnProperty('dutyArea')) {
          canApply = false
        }
      })
      return canApply
    },
    pOpen(row) {
      console.log(row, 'row')
      this.chooseRow = row
      this.showAreaSelectDialog = true
    },
    clearRiskName(row) {
      row.dutyArea = ''
      setTimeout(() => {
        this.treePopover = false
      })
    },
    handleTreeNodeClick(data) {
      this.chooseRow.dutyArea = data.areaName
      this.showAreaSelectDialog = false
    },
    needRectificationChange(value) {
      this.calculateNumberAndText()
      this.initBtn()
    },
    updateData(val, row) {
      // if(val == '1'){
      //
      // }
      this.calculateNumberAndText()
      this.$forceUpdate()
    },
    calculateNumberAndText() {
      let i = 0
      let str = ''
      let str2 = ''
      this.formBaseData.items.forEach((item, index) => {
        if (item.hasOwnProperty('passStatus') && item.passStatus == '2') {
          i++
          str = str + `${item.checkContent}(不通过)；`
          str2 = str2 + `${item.rectificationRequirements}；`
        }
      })
      this.$set(this.formBaseData, 'hiddenDangersNumber', i)
      this.$set(this.formBaseData, 'hiddenPartsAndDescribe', str)
    },
    removeRow(scope) {
      let that = this
      console.log(scope)
      console.log(this.formBaseData.items)
      this.$confirm('确定是否删除本数据？', '提示', {
        confirmButtonClass: 'iconfont icon-icon_ok',
        cancelButtonClass: 'iconfont icon-icon_cancel',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        //判断删除的数据 是子节点：
        // 1、如果有另外的同级子节点，则直接删除选中的节点 。
        // 2、如果是唯一子节点，需要找到其父级，如果父级也是同级唯一，往上递归，如果一直没出现同级有兄的，那就删光，否则就删除到出现同级的时候。
        //如果删除的是父节点
        //  大前提，先把子级全删掉，
        //公共删除子的递归
        let deleteSon = function (data) {
          let code = data.code
          // let parentCode = data.parentCode
          for (let i in that.formBaseData.items) {
            if (that.formBaseData.items[i].parentCode == code) {
              that.formBaseData.items[i].isNeedDelete = true
              deleteSon(that.formBaseData.items[i])
            }
          }
        }
        //删除孤寡节点，判断父级的递归
        let func = function (data) {
          let parentCode = data.parentCode
          let length = 0
          for (let i in that.formBaseData.items) {
            if (that.formBaseData.items[i].parentCode == parentCode) {
              length++
            }
          }
          if (length == 1) {
            for (let j in that.formBaseData.items) {
              if (that.formBaseData.items[j].code == parentCode) {
                that.formBaseData.items[j].isNeedDelete = true
                //删除该 孤寡父节点
                // 递归
                func(that.formBaseData.items[j])
              }
            }
          }
        }
        if (scope.row.hasOwnProperty('checkContent')) {
          let code = scope.row.code
          scope.row.isNeedDelete = true

          func(scope.row)
        } else {
          //删除的是父级，需要删除以它为父的所有子节点和他本身，并且判断它的父
          //如果是顶级
          if (!scope.row.hasOwnProperty('parentCode') || scope.row.parentCode == undefined) {
            scope.row.isNeedDelete = true
            deleteSon(scope.row)
          }
          //如果是中级
          if (scope.row.hasOwnProperty('parentCode') && scope.row.parentCode != undefined) {
            // //如果有父级节点 说明删除的是 中级节点，判断删除之后 判断 有同一父节点的中级节点数量，如果为0 就删除父节点，递归，再判断 父节点和其父父节点的数量关系
            scope.row.isNeedDelete = true
            func(scope.row)
            deleteSon(scope.row)
          }
        }
        //处理属性包含isNeedDelete = 数据
        this.formBaseData.items = this.formBaseData.items.filter(item => {
          if (!item.hasOwnProperty('isNeedDelete')) {
            return item
          }
        })
        //处理vxetable
        for (let i in this.vxeTableCheckData) {
          let flag = false
          for (let j in this.formBaseData.items) {
            if (this.formBaseData.items[j].code == this.vxeTableCheckData[i].code) {
              flag = true
            }
          }
          if (!flag) {
            this.vxeTableCheckData[i].isNeedDelete = true
          }
        }
        //处理属性包含isNeedDelete = 数据
        this.vxeTableCheckData = this.vxeTableCheckData.filter(item => {
          if (!item.hasOwnProperty('isNeedDelete')) {
            return item
          }
        })
      })
      this.$forceUpdate()
    },
    disabledFun({ row }) {
      return this.checkRowKeys.indexOf(row.id) < 0
    },
    selectChangeEvent({ $table }) {
      const records = $table.getCheckboxRecords()
      console.info(`勾选${records.length}个树形节点`, records)
      this.$set(this, 'vxeTableCheckData', records.filter(it => it.hasOwnProperty('checkContent')))

    },
    addNewFile(type) {
      if (type == 1) {
        let obj = {
          stuffName: '新增附件',
          part: `pcnr${this.tableLong++}`,
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        }
        this.buildUnitTable.push(obj)
        this.$forceUpdate()
      }
      if (type == 2) {
        let obj = {
          stuffName: '新增附件',
          part: `zghf${this.tableLong++}`,
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        }
        this.buildUnitTableTwo.push(obj)
        this.$forceUpdate()
      }
      if (type == 3) {

        let obj = {
          stuffName: '新增附件',
          part: `zgys${this.tableLong++}`,
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        }
        this.buildUnitTableThree.push(obj)
        console.log(this.buildUnitTableThree, 'buildUnitTableThree')
        this.$forceUpdate()
      }

    },
    funcActiveMethod() {

    },
    handleChange(val) {
      console.log(val)
      console.log(this.activeCollapse, 'activeCollapse')
    },
    delTableItem(val) {

    },
    getContentFunction(row) {
      return `${(row.hasOwnProperty('isContent') && row.isContent) ? row.content : row.type}`
    },
    closeDialogReset() {
      this.contractListTable = []
      this.showContractListDialog = false
    },
    handleSelectionChange(val) {
      console.log(val)
    },
    getCheckList() {
      this.isLoading = true
      this.$httpPost('/buss/hiddendangeritems/getCheckList', this.search).then(res => {
        if (res.code == 200) {
          // console.log(res)
          this.isLoading = false
          this.$set(this, 'matherData', res.data)
        } else {
          this.$messageError(res.data.message)
          this.isLoading = false
        }
      }).catch(res => {
        this.isLoading = false
        this.$messageError('请求列表失败')
      })
    },
    getAreaList() {
      this.$httpPost('/buss/responsibilityarea/listPage', {
        sectionId: this.search.sectionId,
        projectId: this.search.projectId
      }).then(res => {
        if (res.code == 200) {
          console.log(res)
          console.log(this.buildTree(res.data.content), 'cvvvvvvvvvvvvvvvv')
          this.$set(this, 'areaList', this.buildTree(res.data.content))
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        this.$messageError('请求列表失败')
      })
    },
    buildTree(data) {
      let map = {}
      data.forEach((node) => {
        map[node.id] = node
        node.children = []
      })
      let roots = []

      data.forEach((node) => {
        if (node.pid !== '0') {
          map[node.pid].children.push(node)
        } else {
          roots.push(node)
        }
      })
      return roots
    },
    selectworklist() {
      this.showContractListDialog = true
      this.$set(this, 'contractListTable', JSON.parse(JSON.stringify(this.matherData)))
      this.$nextTick(() => {
        this.$set(this, 'checkRowKeys', this.vxeTableCheckData.map(it => it.id))
        console.log(this.vxeTableCheckData, 'this.vxeTableCheckData')
        this.$set(this, 'checkRowKeysByName', this.vxeTableCheckData.map(it => it.id))
        console.log(this.checkRowKeys)
        this.$forceUpdate()
      })

    },
    changeTab(index) {
      this.activeIndex = index
    },
    showRowTable() {
      if (this.detailType == 'check' || this.detailType == 'approve') {
        return true
      } else {
        return false
      }
    },
    setPosition(val) {
      console.log(val, '获取的经纬度')
      this.$set(this.formBaseData, 'longitude', val.JD ? val.JD : '--')
      this.$set(this.formBaseData, 'latitude', val.WD ? val.WD : '--')
      this.$set(this.formBaseData, 'location', val.positionName ? val.positionName : '--')
    },
    showPicker() {
      this.showPickerObj = {
        show: true,
        projectId: this.search.projectId
      }
    },
    getInspectionLevel() {
      crudDict.getByCode('inspectionLevel').then(res => {
        if (res.code == 200) {
          this.inspectionLevelList = res.data
        }
      })
    },
    startChange(value, row) {
      this.startTimeOptions.disabledDate = time => {
        if (row) {
          if (time.getTime() > new Date(row).getTime()) {
            return true
          }
        }
        // if(time.getTime() > Date.now()){
        //   return true
        // }
      }
    },

    endChange(value, row) {
      this.endTimeOptions.disabledDate = time => {
        if (row) {
          if (time.getTime() < new Date(row).getTime()) {
            return true
          }
        }
        // if(time.getTime() > Date.now()){
        //   return true
        // }
      }
    },
    genReport(id) {
      this.$httpPost('/buss/safetyRectification/genReport', {
        id: id
      }).then(res => {

        console.log(res)
      }).catch(res => {
        console.log(res)
      })
    },
    genReportReply(id) {
      this.$httpPost('/buss/safetyRectification/genReportReply', {
        id: id
      }).then(res => {

        console.log(res)
      }).catch(res => {
        console.log(res)
      })
    },
    changeSectionInfo() {
      this.initBtn()
      this.formBaseData.constructionUnitName = ''
      this.formBaseData.supervisorUnitName = ''
      this.formBaseData.constructionUnitId = ''
      this.formBaseData.supervisorUnitId = ''
      sectionInfo.getCompanyBySectionId(this.formBaseData.sectionId).then(res => {
        if (res.status === 1) {
          var data = res.data
          this.formBaseData.constructionUnitName = data.buildUnit
          this.formBaseData.supervisorUnitName = data.supervisorUnit
          this.formBaseData.constructionUnitId = data.buildUnitId
          this.formBaseData.supervisorUnitId = data.supervisorUnitId
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2('获取标段相关单位失败')
      })
    },
    onComplete(data) {
      this.wfNode = data
    },
    onApprove(params, callback) {  //UserTask_0eanxae
      if (this.detailType == 'approve' && this.formBaseData.taskKey == 'UserTask_10jkn5c' || this.detailType == 'approve' && this.formBaseData.taskKey == 'UserTask_1xxftgv') {
        if (!this.formBaseData.replyCode) {
          msgUtil.error2('请输入回复单号')
          callback && callback()
          return
        }
        if (!this.formBaseData.rectificationMeasures) {
          msgUtil.error2('请输入整改结果')
          callback && callback()
          return
        }
        if (!this.formBaseData.rectificationCompletionDate) {
          msgUtil.error2('请选择整改完成日期')
          callback && callback()
          return
        }
        if (!this.formBaseData.headRectification) {
          msgUtil.error2('请填写整改负责人')
          callback && callback()
          return
        }
      }
      let arr1 = this.buildUnitTable.map(item => {
        return {
          part: item.part,
          stuffName: item.stuffName
        }
      })
      let arr2 = this.buildUnitTableTwo.map(item => {
        return {
          part: item.part,
          stuffName: item.stuffName
        }
      })
      let arr3 = this.buildUnitTableThree.map(item => {
        return {
          part: item.part,
          stuffName: item.stuffName
        }
      })
      this.formBaseData.fileStr = {
        'pcnr': arr1,
        'zghf': arr2,
        'zgys': arr3
      }

      // 整改回复验证
      let index = this.tabs.findIndex(e => e == '整改回复')
      if (index !== -1) {
        if (!this.formBaseData.rectificationCompletionDate) {
          msgUtil.error2('请选择整改完成日期!')
          callback && callback()
          return
        }
        if (!this.formBaseData.headRectification) {
          msgUtil.error2('请填写整改负责人!')
          callback && callback()
          return
        }
        if (!this.formBaseData.replyCode) {
          msgUtil.error2('请填写回复单编号!')
          callback && callback()
          return
        }
        if (!this.formBaseData.rectificationMeasures) {
          msgUtil.error2('请填写处理意见执行情况!')
          callback && callback()
          return
        }
      }

      const dealForm = this.$refs.bpmnForm.getForm()
      this.approveForm.procDefKey = 'safetyRectificationProcess'
      this.approveForm.businessId = this.formBaseData.id
      this.approveForm.procInstId = this.formBaseData.procInstId
      this.approveForm.description = dealForm.description
      this.approveForm.hiddenPartsAndDescribe = dealForm.hiddenPartsAndDescribe
      this.approveForm.selectAssigneeList = dealForm.selectAssigneeList
      if (params.isReject != '1') {
        if (this.$refs.bpmnForm.showUserSelect) {
          if (!dealForm.selectAssigneeList.length) {
            msgUtil.error2('请选择处理人!')
            callback && callback()
            return
          }
        }
      }
      if (Array.isArray(this.formBaseData.checkQuestionType)) {
        this.formBaseData.checkQuestionType = this.formBaseData.checkQuestionType.join(",")
      }
      if (Array.isArray(this.formBaseData.worksCategory)) {
        this.formBaseData.worksCategory = this.formBaseData.worksCategory.join(",")
      }
      this.approveForm.entity = this.formBaseData
      this.approveForm.problem = this.formBaseData.needRectification
      // 覆盖按钮参数
      Object.assign(this.approveForm, params)
      safetyRectification.audit(this.approveForm).then(r => {
        this.detailId = this.formBaseData.id
        //this.saveFiles()
        //  this.genReport(this.formBaseData.id)
        this.saveFiles().then(() => {
          /*      if(this.formBaseData.taskKey=='UserTask_1xxftgv'||this.formBaseData.taskKey=='UserTask_10jkn5c'
                  ||this.formBaseData.taskKey=='UserTask_0adgz3j'||this.formBaseData.taskKey=='UserTask_0dr74a3'
                  ||this.formBaseData.taskKey=='UserTask_05hh80t'||this.formBaseData.taskKey=='UserTask_05hsrzg'){
                  this.genReportReply(this.formBaseData.id)
                }*/
          this.genReport(this.formBaseData.id)
          this.genReportReply(this.formBaseData.id)
          msgUtil.success2('审批成功!')
          this.formShow = false
          this.$emit('reloadList')

        })

      }).finally(() => {
        callback && callback()
      })
    },
    onApply(_, callback) {
      let startForm = {}
      let arr1 = this.buildUnitTable.map(item => {
        return {
          part: item.part,
          stuffName: item.stuffName
        }
      })
      let arr2 = this.buildUnitTableTwo.map(item => {
        return {
          part: item.part,
          stuffName: item.stuffName
        }
      })
      let arr3 = this.buildUnitTableThree.map(item => {
        return {
          part: item.part,
          stuffName: item.stuffName
        }
      })
      this.formBaseData.fileStr = {
        'pcnr': arr1,
        'zghf': arr2,
        'zgys': arr3
      }
      if (this.formBaseData.items.length > 0) {
        this.formBaseData.items.forEach((item, index) => {
          item.checkId = item.id
        })
      }
      startForm.entity = this.formBaseData
      startForm.procDefKey = 'safetyRectificationProcess'
      startForm.businessId = this.formBaseData.id
      startForm.variables = this.variables
      const dealForm = this.$refs.bpmnForm.getForm()
      startForm.variables.problem = this.formBaseData.needRectification
      startForm.selectAssigneeList = dealForm.selectAssigneeList

      if (!dealForm.selectAssigneeList.length) {
        msgUtil.error2('请选择处理人!')
        callback && callback()
        return
      }
      if (this.formBaseData.needRectification == '1') {
        if (!this.formBaseData.rectificationDeadline) {
          msgUtil.error2('请选择整改截止日期')
          callback && callback()
          return
        }
        // if (!this.formBaseData.noticeNum) {
        //   msgUtil.error2('请填写通知单号')
        //   callback && callback()
        //   return
        // }
        if (!this.formBaseData.dateIssue) {
          msgUtil.error2('请选择签发日期')
          callback && callback()
          return
        }
        // if (!this.formBaseData.checkQuestionType) {
        //   msgUtil.error2('请选择问题类型')
        //   callback && callback()
        //   return
        // }
        // if (!this.formBaseData.worksCategory) {
        //   msgUtil.error2('请选择工程类别')
        //   callback && callback()
        //   return
        // }

        if (!this.formBaseData.suggestedRectificationMeasures) {
          msgUtil.error2('请输入整改要求')
          callback && callback()
          return
        }
        if (!this.formBaseData.existingProblems) {
          msgUtil.error2('请输入存在问题')
          callback && callback()
          return
        }
        if (!this.formBaseData.hiddenPartsAndDescribe) {
          msgUtil.error2('请填写隐患部位及描述')
          callback && callback()
          return
        }
      }
      // if (!this.checkoutArea()) {
      //   this.$messageWarning('请选择不通过检查内容的责任区域')
      //   callback && callback()
      //   return
      // }
      if (Array.isArray(this.formBaseData.checkQuestionType)) {
        this.formBaseData.checkQuestionType = this.formBaseData.checkQuestionType.join(",")
      }
      if (Array.isArray(this.formBaseData.worksCategory)) {
        this.formBaseData.worksCategory = this.formBaseData.worksCategory.join(",")
      }
      this.$refs['formBaseData'].validate((valid) => {
        if (valid) {

          safetyRectification.report(startForm).then(r => {
            if (r.code == 200) {
              this.detailId = r.data.businessId

              this.saveFiles().then(() => {
                if (typeof r.data.businessId == "undefined" || r.data.businessId == undefined) {
                } else {
                  this.genReport(r.data.businessId)
                }

                this.formShow = false
                this.$emit('reloadList')
                this.$notify({
                  title: '安全整改保存成功',
                  type: 'success',
                  duration: 1500
                })
              })
              this.formShow = false
              this.$emit('reloadList')
              this.$notify({
                title: '上报成功',
                type: 'success',
                duration: 1500
              })
            }
          }).finally(() => {
            callback && callback()
          })
        } else {
          callback && callback()
        }
      })
    },

    cancel() {
      this.handleClickDeal('cancel')
    },

    onSave(_, callback) {
      this.submitAudit(callback)
    },

    initBtn() {

      if (this.detailType === 'build' || (this.detailType === 'edit' && this.formBaseData.status == 0)) {

        dept.getOne(this.user.companyId).then(res => {
          if (res.code === 200) {
            var data = res.data;
            //监理单位
            if (data.companyType.indexOf("dd586947e1204b2e9157967b7528a7a9") > -1) {
              this.formBaseData.initiator = 2
              this.variables = { initiator: 2 }
            }
            //建设单位
            else if (data.companyType.indexOf("80beb78c7b374b69b183adbb233ddfd5") > -1) {
              this.formBaseData.initiator = 1
              this.variables = { initiator: 1 }

            }

            if (this.formBaseData.initiator && this.formBaseData.initiator == '' || !data.companyType) {
              this.$messageWarning('当前登录人不是业主单位、监理单位不能上报本模块！')
              this.cancel()
            }

          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch(() => {
          msgUtil.error2("获取登录人建设单位类型失败")
        })
      }
      if (Array.isArray(this.formBaseData.checkQuestionType)) {
        this.formBaseData.checkQuestionType = this.formBaseData.checkQuestionType.join(",")
      }
      if (Array.isArray(this.formBaseData.worksCategory)) {
        this.formBaseData.worksCategory = this.formBaseData.worksCategory.join(",")
      }
      const params = {
        businessId: this.formBaseData.id,
        procDefKey: 'safetyRectificationProcess',
        url: this.url,
        entity: this.formBaseData,
        variables: this.variables

      }
      params.variables.initiator = this.formBaseData.initiator
      params.variables.problem = this.formBaseData.needRectification
      this.$refs.bpmnForm && this.$refs.bpmnForm.initNodeAttribute(params)
      this.$refs.btn && this.$refs.btn.getBtnListWithParam(params)
    },
    initData() {
      this.companyTree = []

      projectSectionInfo.getProjectSectionInfoTree().then(res => {
        if (res.code === 200) {
          var data = res.data
          this.companyTree = data
          if (this.detailType == 'build' && this.companyTree.length > 0) {

            this.formBaseData.companyId = this.companyTree[0].id
            this.getProjectByCompanyId()
          } else {
            this.getProjectByCompanyId()
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch((e) => {
        console.log(e)
        msgUtil.error2('获取项目标段树失败')
      })

    },
    /**
     *  根据建设单位查询下面的所有项目
     * */
    getProjectByCompanyId() {

      this.companyTree.forEach((item) => {
        // if (item.id === this.formBaseData.companyId) {
        this.projectTree = item.children
        if (this.detailType == 'build' && this.projectTree.length > 0) {

          this.formBaseData.projectId = this.projectTree[0].id
          this.formBaseData.projectName = this.projectTree[0].name
          this.getSectionByProjectId()
        } else {
          this.getSectionByProjectId()
        }
        // }
      })
    },

    /**
     * 根据项目id获取标段列表
     * getContractByProjectId
     * */
    getSectionByProjectId() {

      if (this.formBaseData.sectionId && !this.checkInitShow) {
        this.formBaseData.sectionId = ''
      }

      if (this.checkInitShow) {
        this.checkInitShow = false
      }

      if (this.formBaseData.projectId) {
        this.projectTree.forEach((item) => {
          if (item.id == this.formBaseData.projectId) {
            this.sectionTree = item.children
            if (this.detailType == 'build' && this.sectionTree.length > 0) {
              this.formBaseData.sectionId = this.sectionTree[0].id
              this.formBaseData.sectionName = this.sectionTree[0].name
              this.changeSectionInfo()
            }
          }
        })
      }
    },

    /**
     * 重置主表数据
     * */
    resetFormData() {
      this.formBaseData = {
        user: {},
        initiator: 1,
        needRectification: '2',
        hiddenPartsAndDescribe: '',
        hiddenDangersNumber: '',
        projectName: '',
        sectionName: '',
        inspector: '',
        inspectionTime: '',
        inspectionLevel: '',
        longitude: '',
        latitude: '',
        suggestedRectificationMeasures: '',
        rectificationDeadline: '',
        hiddenInformation: '',
        projectId: '',
        sectionId: '',
        rectificationMeasures: '',
        rectificationStartDate: '',
        rectificationCompletionDate: '',
        headRectification: '',
        acceptanceCondition: '',
        //  标题
        title: '',
        rectificationDate: '',
        isAuditUpdate: 0,
        opinion: '',
        checkUser: '',
        checkDate: '',
        constructionTeam: '',
        isRectification: '2',
        isNotice: '2',
        problemType: '',
        urgency: '',
        lon: '',
        lat: '',
        location: '',
        locationAll: '',
        checkTime: '',
        items: [],
        fileStr: '',
        note: '',
        noticeNum: '',
        dateIssue: '',
        checkQuestionType: '',
        worksCategory: '',
        categoryName: '',
        parts: '',
        existingProblems: '',
        headPerson: '',
        replyCode: '',
        zghf: true,
        zgys: true
      }
      this.taskDefKey = ''
      this.entityId = ''
    },

    /***
     * 提交保存数据
     * */
    submit(flag, callback) {
      let url = this.url.submit
      if (this.detailType !== 'build') {
        url = this.url.resubmit
      }

      if (this.taskDefKey != null && this.taskDefKey != undefined && this.taskDefKey != '') {
        this.formBaseData.isAuditUpdate = 1
      }
      if (this.taskDefKey == null || this.taskDefKey == undefined || this.taskDefKey == '') {
        this.formBaseData.isAuditUpdate = 0
      }
      this.formBaseData.contractId = this.contractId
      this.$httpPost(url, this.formBaseData).then(res => {
        if (res.data.status === 1) {
          this.$messageSuccess('保存成功')
          this.formShow = false
          this.detailId = res.data.id
          this.isLoading = false
          if (callback) callback(res.data)
        } else {
          this.isLoading = false
          this.$messageError(res.data.message)
        }
      }).catch(e => {
        console.log('请求出现错误', e)
        this.isLoading = false
        console.log('提交失败', e)
        this.$messageError('请求失败')
      })
    },
    /**
     * 获取详情并整理数据
     * */
    getDetail() {
      safetyRectification.getOne(this.detailBaseId).then(res => {
        if (res.code == 200) {
          let data = res.data
          data.checkQuestionType = data.checkQuestionType ? data.checkQuestionType.split(",") : []
          data.worksCategory = data.worksCategory ? data.worksCategory.split(",") : []
          this.formBaseData = data
          if (!this.search.projectId) {
            this.search.projectId = data.projectId
            this.search.projectName = data.projectName
            this.getCheckList()//获取检查清单
          }
          this.getZghf()
          this.getZgys()
          // 审核情况下，跳转到编辑切页
          if (this.detailType == 'approve') {
            if (!this.formBaseData.zghf) {
              this.activeIndex = 2
            } else if (!this.formBaseData.zgys) {
              this.activeIndex = 3
            }
          }

          let arr = this.formBaseData.items.filter(it => it.hasOwnProperty('checkContent'))
          // console.log(arr, 'arr')
          arr.forEach((item, index) => {
            item.id = item.checkId
          })
          this.$set(this, 'vxeTableCheckData', arr)
          // if(this.formBaseData.location){
          //   this.formBaseData.locationAll = this.formBaseData.location+'('+this.formBaseData.lon+','+this.formBaseData.lat+')'
          // }
          this.$nextTick(() => {
            this.detailId = this.detailBaseId
            let dataStr = JSON.parse(this.formBaseData.fileStr)
            // console.log(dataStr, 'dataStr')
            if (dataStr.pcnr.length > 0) {
              dataStr.pcnr.forEach((item, index) => {
                item.isNeed = false
                item.loading = false
                item.isMulti = true
                item.file = [{ realName: '' }]
              })
            }
            if (dataStr.zghf.length > 0) {
              dataStr.zghf.forEach((item, index) => {
                item.isNeed = false
                item.loading = false
                item.isMulti = true
                item.file = [{ realName: '' }]
              })
            }
            if (dataStr.zgys.length > 0) {
              dataStr.zgys.forEach((item, index) => {
                item.isNeed = false
                item.loading = false
                item.isMulti = true
                item.file = [{ realName: '' }]
              })
            }
            if (dataStr.pcnr.length > 0) {
              this.buildUnitTable = [...dataStr.pcnr]
            }
            if (dataStr.zghf.length > 0) {
              this.buildUnitTableTwo = [...dataStr.zghf]
            }
            if (dataStr.zgys.length > 0) {
              this.buildUnitTableThree = [...dataStr.zgys]
            }
            this.$forceUpdate()
            console.log(this.buildUnitTable, '1')
            console.log(this.buildUnitTableTwo, '2')
            console.log(this.buildUnitTableThree, '3')
          })
          this.checkInitShow = true
          this.getProjectByCompanyId()
          if (this.detailType == 'approve' || this.detailType == 'edit') {
            this.initBtn()
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2('获取详情信息失败')
      })

    },
    /**
     * 审批提交成功的回调函数
     * */
    onAuditSubmitSuccess() {
      //  关闭查看框并刷新列表
      this.formShow = false
      this.$emit('reloadList')
    },
    /**
     * 选中流程动作选项时的回调函数
     * */
    onSeledAuditAction() {
      this.showAuditBtn = true
    },
    /*{
      '排查内容':[{
      part: 'xxx1',
      name: 'sssss 文件'
    },{
      part: 'xxx2',
      name: 'sssss 文件'
    }],
      整改回复:[{
      part: 'xxx1',
      name: 'sssss 文件'
    },{
      part: 'xxx2',
      name: 'sssss 文件'
    }],

    }*/
    submitAudit(callback) {
      this.$refs['formBaseData'].validate((valid) => {
        if (valid) {
          let arr1 = this.buildUnitTable.map(item => {
            return {
              part: item.part,
              stuffName: item.stuffName
            }
          })
          let arr2 = this.buildUnitTableTwo.map(item => {
            return {
              part: item.part,
              stuffName: item.stuffName
            }
          })
          let arr3 = this.buildUnitTableThree.map(item => {
            return {
              part: item.part,
              stuffName: item.stuffName
            }
          })
          this.formBaseData.fileStr = {
            'pcnr': arr1,
            'zghf': arr2,
            'zgys': arr3
          }
          if (this.formBaseData.items.length > 0) {
            this.formBaseData.items.forEach((item, index) => {
              item.checkId = item.id
            })
          }
          if (this.detailType === 'build') {
            if (Array.isArray(this.formBaseData.checkQuestionType)) {
              this.formBaseData.checkQuestionType = this.formBaseData.checkQuestionType.join(",")
            }
            if (Array.isArray(this.formBaseData.worksCategory)) {
              this.formBaseData.worksCategory = this.formBaseData.worksCategory.join(",")
            }
            this.formBaseData.status = 17
            this.formBaseData.nodeName = "检查完成"

            safetyRectification.submit(this.formBaseData).then(res => {
              if (res.code === 200) {
                this.detailId = res.data.id
                console.log(this.detailId)
                this.saveFiles().then(() => {
                  this.genReport(res.data.id)
                  this.formShow = false
                  this.$emit('reloadList')
                  this.$notify({
                    title: '安全整改保存成功',
                    type: 'success',
                    duration: 1500
                  })
                })

              } else {
                msgUtil.error2(res.data.message)
              }
            }).catch((response) => {
              console.log(response)
              this.$notify({
                title: '安全整改保存失败',
                type: 'error',
                duration: 2500
              })
            }).finally((response) => {
              callback && callback()
            })
          } else {
            if (Array.isArray(this.formBaseData.checkQuestionType)) {
              this.formBaseData.checkQuestionType = this.formBaseData.checkQuestionType.join(",")
            }
            if (Array.isArray(this.formBaseData.worksCategory)) {
              this.formBaseData.worksCategory = this.formBaseData.worksCategory.join(",")
            }
            safetyRectification.resubmit(this.formBaseData).then(res => {
              if (res.code === 200) {
                this.detailId = res.data.id
                console.log(this.detailId)
                this.saveFiles().then(() => {
                  this.genReport(res.data.id)
                  this.formShow = false
                  this.$emit('reloadList')
                  this.$notify({
                    title: '项目自检保存成功',
                    type: 'success',
                    duration: 1500
                  })
                })

                // 传值给父组件刷新列表
                this.$notify({
                  title: '数据修改成功',
                  type: 'success',
                  duration: 1500
                })
                this.$emit('reloadList')
                this.formShow = false
              } else {
                msgUtil.error2(res.data.message)
              }
            }).catch((response) => {
              this.$notify({
                title: '数据修改失败',
                type: 'error',
                duration: 2500
              })
            }).finally((response) => {
              callback && callback()
            })
          }
        } else {
          callback && callback()
        }
      })
    },
    async saveFiles() {
      let queue = []
      if (this.formBaseData.needRectification == 2) {
        queue.push(this.$refs['cmsFileTable_one'].bindAllFile(this.detailId))
      }
      if (this.formBaseData.needRectification == 1) {
        queue.push(this.$refs['cmsFileTable_one'].bindAllFile(this.detailId))
        queue.push(this.$refs['cmsFileTable_Two'].bindAllFile(this.detailId))
        queue.push(this.$refs['cmsFileTable_Three'].bindAllFile(this.detailId))
      }
      const res = await Promise.all(queue)
      return res
    },

    /**
     * 控制上传按钮显示
     * @param row
     * @returns {boolean}
     */
    buttonUploadShow(row) {
      let flag = false

      if (this.detailType === 'build' || this.detailType === 'edit') {
        flag = true
      }
      return flag
    },
    buttonUploadShow2(row) {
      let flag = false
      //原来的代码(this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_0u6ln5c') || (this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_10jkn5c') || (this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_1xxftgv')
      //UserTask_1sci9cl:施工单位经办人
      if (this.detailType === 'approve' && (['UserTask_1sci9cl', 'UserTask_0u6ln5c', 'UserTask_10jkn5c', 'UserTask_1xxftgv'].indexOf(this.formBaseData.taskKey) !== -1)) {
        flag = true
      } else {
        flag = false
      }
      return flag
    },
    buttonUploadShow3(row) {
      let flag = false
      if ((this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_0t9gy8c')
        || (this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_0bm9j9l')) {
        flag = true
      }
      return flag
    },
    /**
     * 控制查看按钮显示
     * @param row
     */
    buttonCheckShow(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName !== ''
      ) {
        flag = true
      }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },
    /**
     *控制显示暂无文件
     * @param row
     */
    showNone(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName === ''
      ) {
        flag = true
      }
      if (this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_sgdwzg') {
        if (row.stuffName == '整改单位附件') {
          flag = false
        }
      }
      return flag
    },
    showNone2(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName === ''
      ) {
        flag = true
      }
      if (this.detailType === 'approve' && row.file[0].realName === '') {
        flag = false
      }

      return flag
    },
    showNone3(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName === ''
      ) {
        flag = true
      }
      if (this.detailType === 'approve' && row.file[0].realName === '') {
        flag = false
      }
      if (this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_0t9gy8c') {
        flag = false
      }
      return flag
    },
    /**
     *显示删除按钮
     * @param row
     */
    buttonDelShow(row) {
      let flag = false
      if (
        (this.detailType === 'build' || this.detailType === 'edit') &&
        row.file[0].realName !== '' &&
        !row.isNeed
      ) {
        flag = true
      }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },
    ////////////////////////////////以上是附件上传所需代码

    tableChange(val, type) {
      if (type == 'cmsFileTable_one') {
        this.$set(this, 'buildUnitTable', [...val])

      }
      if (type == 'cmsFileTable_Two') {
        this.$set(this, 'buildUnitTableTwo', [...val])

      }
      if (type == 'cmsFileTable_Three') {
        this.$set(this, 'buildUnitTableThree', [...val])

      }
    },
    addList() {
      //调接口
      //打开dialog
      this.showSelectDialog = true
    },
    handleClick(activeName) {
      console.log(activeName)
    },
    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost(
        this.$store.state.httpHost.buss + url + query,
        params
      ).then(res => {
        if (res.data.status === 1) {
          if (callback) callback(res.data)
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        console.log(res)
      })
    },
    handleTreeData(treeData) {
      if (!treeData || treeData.length === 0) {
        return []
      }
      const array = []
      for (let i = 0; i < treeData.length; i += 1) {
        let match = false
        if (treeData[i].hasOwnProperty('isSelect') && treeData[i].isSelect != false) {
          match |= (treeData[i].hasOwnProperty('isSelect'))
          if (!match) break
        }
        if (this.handleTreeData(treeData[i].children).length > 0 || match) {
          console.log(treeData[i], 'cccccccc')
          array.push({
            ...treeData[i],
            children: this.handleTreeData(treeData[i].children)
          })
        }
      }
      return array
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          this.$set(this, 'checkRowKeys', [])
          this.$set(this, 'vxeTableCheckData', [])
          this.$set(this, 'contractListTable', [])
          this.activeCollapse = ['1', '2']
          this.activeCollapseTwo = ['3']
          this.activeCollapseThree = ['4']
          this.showContractListDialog = false
          this.areaList = []
          this.selectedIds = []
          this.activeIndex = 0
          this.buildUnitTable = []
          this.buildUnitTableTwo = []
          this.buildUnitTableThree = []
          this.formBaseData.needRectification = '2'
          this.activeIndex = 0
          // 清空表单内容
          this.resetFormData()
          this.fileList = []
          if (this.$refs.bpmnForm && this.$refs.bpmnForm.form.selectAssigneeList) {
            this.$refs.bpmnForm.form.selectAssigneeList = []
          }
          if (this.$refs.bpmnForm && this.$refs.bpmnForm.form.hiddenPartsAndDescribe) {
            this.$refs.bpmnForm.form.hiddenPartsAndDescribe = ''
          }
          this.detailId = ''
          this.detailBaseId = ''
          this.isShowBpmn = false
          // 关闭弹窗
          this.formShow = false
          break
        // 保存
        case 'submit':
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 再验证其他内容
              // 整理文件信息
              this.isLoading = true
              // 提交详情

              this.submitAudit(_, () => {
                this.isLoading = false
                // 传值给父组件刷新列表
                this.$emit('reloadList')
              })
            }
          })
          break
        case 'selected':
          // aaaaa
          let detailRowArr = (JSON.parse(JSON.stringify(this.formBaseData.items))).map(i => i.code)
          console.log(this.vxeTableCheckData, 'nnnnnnnnnnnnnnnnn')
          let fatherIdsAll = []
          let fatherIds = []
          let fatherArr = []
          let fatherLoseIds = []
          let postArr = []
          this.vxeTableCheckData.forEach((item, index) => {
            if (this.checkRowKeys.indexOf(item.id) < 0) {
              //勾选的数据 统一赋值 通过
              if (item.hasOwnProperty('checkContent')) {
                item.passStatus = '1'
                fatherIdsAll.push(item.parentCode)
              } else {
                fatherArr.push(item)
              }
              postArr.push(item)
              this.formBaseData.items.push(item)
            }
          })

          fatherIds = Array.from(new Set(JSON.parse(JSON.stringify(fatherIdsAll))))
          //存在的父级数组 fatherArr
          //应该存在的父级ids fatherIds
          let arr1 = fatherArr.map(it => it.code)

          for (let i in fatherIds) {
            if (!arr1.includes(fatherIds[i]) && !detailRowArr.includes(fatherIds[i])) {
              fatherLoseIds.push(fatherIds[i])
            }
          }

          console.log(this.formBaseData.items, 'ccccccccccc')

          //判断detail页面的父id  和 内页面的父id
          if (fatherLoseIds.length > 0) {
            this.findFatherById(fatherLoseIds, detailRowArr)
          } else {
            //说明是全的，但是只针对子级和他的上一级父级
            // 判断是否有父父级
            let arrCode = Array.from(new Set(JSON.parse(JSON.stringify(fatherArr.map(it => it.code)))))
            let arr1Parent = Array.from(new Set(JSON.parse(JSON.stringify(fatherArr.map(it => it.parentCode)))))

            for (let i in arr1Parent) {
              let hasFatherCode = false
              for (let j in arrCode) {
                if (fatherArr[i].parentCode == fatherArr[j].code) {
                  hasFatherCode = true
                }
              }
              if (!hasFatherCode) {
                fatherLoseIds.push(arr1Parent[i])
              }
            }
            this.findFatherById(fatherLoseIds, detailRowArr)
          }
          this.showContractListDialog = false
          // this.contractListTable = []
          this.activeCollapse = ['1', '2']
          break
        case 'selectedcancel':
          let arr = []
          this.vxeTableCheckData.forEach((item, index) => {
            if (this.checkRowKeys.indexOf(item.id) > -1) {
              arr.push(item)
            }
          })
          this.$set(this, 'vxeTableCheckData', arr)
          //vxeTableCheckData 是勾选的所有数据，包括 新的和旧的，
          this.showContractListDialog = false
      }
    },
    findFatherById(ids, alReadyId) {
      let that = this
      console.log(ids, '缺少的father code')
      let fatherArr = []
      let bianpingArr = []

      let func = function (list) {
        let res = []
        res = list.concat(...list.map(item => {
          if (item.childList instanceof Array && item.childList.length > 0 && !item.childList[0].hasOwnProperty('checkContent')) {
            return func(item.childList)
          }
          return null
        }).filter(o => o instanceof Array && o.length > 0))
        return res
      }
      bianpingArr = func(this.contractListTable)

      console.log(bianpingArr)
      let fun = function (code) {
        let itemCodes = that.formBaseData.items.map(it => it.code)
        for (let j in bianpingArr) {
          if (bianpingArr[j].code == code && !itemCodes.includes(code)) {
            that.formBaseData.items.push(bianpingArr[j])
            if (bianpingArr[j].hasOwnProperty('parentCode')) {
              //递归下一次
              fun(bianpingArr[j].parentCode)
            } else {
              continue
            }
          }
        }
      }
      for (let i in ids) {
        for (let j in bianpingArr) {
          if (ids[i] == bianpingArr[j].code) {
            if (!alReadyId.includes(ids[i])) {
              this.formBaseData.items.push(bianpingArr[j])
            }
            if (bianpingArr[j].hasOwnProperty('parentCode') && !alReadyId.includes(bianpingArr[j].parentCode)) {
              let isHave = false
              for (let t in this.formBaseData.items) {
                if (this.formBaseData.items[t].code == bianpingArr[j].parentCode) {
                  isHave = true
                }
              }
              if (isHave == false) {
                fun(bianpingArr[j].parentCode)
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}

.el-input__inner {
  width: 291px;
}

.secondPanTop {
  .el-button--primary {
    color: #409eff;
    background-color: #ffffff;
    font-size: 13px;
    padding: 10px 5px;
  }
}

.flex {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.flex-center {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.dialogTableDiv {
  width: 100%;
  margin: 0 auto;

  .tableTitle {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;

    p {
      font-size: 16px;
    }

    .add {
      background-color: #ffffff;
      color: rgb(73, 163, 250);
    }
  }
}

.meterage-manage-detail
  .el-date-editor.el-input.el-input--prefix.el-input--suffix.el-date-editor--date {
  width: 255px;
}

.flex-row-center {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.content-box {
  border: 1px solid #e2e8ec;
  min-height: 500px;
  margin-top: 20px;
  display: flex;
  flex-direction: row;

  .left-box {
    border-right: 1px solid #e2e8ec;
    padding: 20px 0px 0px 40px;
    width: 200px;
    min-height: 100%;

    p {
      cursor: pointer;
      font-size: 15px;
    }

    .active {
      color: #3366cc;
      font-weight: bold;
    }
  }

  .right-box {
    width: calc(100% - 200px);
    height: 100%;
    padding: 20px 20px;

    .text-link {
      cursor: pointer;
      color: #3366cc !important;

      &:hover {
        text-decoration: underline;
      }
    }

    .text-link-split {
      color: #3366cc !important;
    }

    .form-input {
      width: 100%;
    }

    .question-box {
      height: 300px;
      border-bottom: 1px solid #e2e8ec;
      // border-top: 1px solid #e2e8ec;
      display: flex;

      .question-left-box {
        border-right: 1px solid #e2e8ec;
        padding: 20px 5px;
        width: 140px;
        height: 100%;
        display: flex;
        flex-direction: column;

        .question-left-item {
          margin-bottom: 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;

          span,
          i {
            cursor: pointer;
            font-size: 15px;
          }
        }

        .active {
          span {
            color: #3366cc;
            font-weight: bold;
          }
        }

        .add-question {
          margin-top: auto;
          border: 1px solid #3366cc !important;
          color: #3366cc !important;
          background-color: transparent !important;
        }
      }

      .question-right-box {
        width: calc(100% - 140px);
        height: 100%;
        padding-left: 10px;
      }
    }
  }
}

.flex-align-center {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.changecost_contract_list {
  margin: 25px;

  .head {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;

    .headLeft {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
<style lang="scss">
.el-message-box {
  .el-message-box__btns {
    .el-button {
      font-size: 14px;
    }
  }
}
</style>

